import random
import time

from rest_framework.viewsets import GenericViewSet, ViewSet
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework_jwt.serializers import jwt_decode_handler

from user.models import User, CodeImg, Info, Track, Coupon
from user.serializers import UserShowSerializer, UserlogonSerializer, GuestInfoSerializer
from user.serializers import CodeImgShowSerializer, UserLoginSerializer, GetUserInfoSerialize
from user.serializers import UpdateNicknameSerializer, TrackShowSerializer
from utils.responses import CommonResponse


class UserShowView(GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserShowSerializer

    def get_users(self, request, *args, **kwargs):
        user_list = self.get_queryset()
        user_ser = self.get_serializer(instance=user_list, many=True)
        return CommonResponse(data=user_ser.data)


class UserLogonView(ViewSet):
    def user_logon(self, request, *args, **kwargs):
        user_ser = UserlogonSerializer(data=request.data)
        if user_ser.is_valid():
            instance = user_ser.save()
            return CommonResponse(tip='用户注册成功', user_id=instance.id)
        else:
            error = user_ser.errors.get('non_field_errors')[0]
            return CommonResponse(state=0, tip='用户注册失败', error=error)


class GuestInfoView(ViewSet):
    def guest_info(self, request, *args, **kwargs):
        guest_ser = GuestInfoSerializer(data=request.data)
        if guest_ser.is_valid():
            guest_ser.save()
            return CommonResponse(tip='食客信息已完善')
        else:
            error = guest_ser.errors.get('non_field_errors')[0]
            return CommonResponse(state=0, tip='食客信息建立失败', error=error)


class CodeImgShowView(GenericViewSet):
    queryset = CodeImg.objects.filter(is_use=True)
    serializer_class = CodeImgShowSerializer

    def get_code_img(self, request, *args, **kwargs):
        code_img_list = self.get_queryset()
        code_img_ser = self.get_serializer(instance=code_img_list, many=True)
        return_list = code_img_ser.data
        random.shuffle(return_list)
        rule_list = [
            [1, '图中最帅的是？', '这题送分啊'],
            [2, '图中曾经体重超过200的是？', '提示，曾经是木木，现在变成了老林'],
            [3, '图中实际年龄最大的是？', '老男孩人均18，除了***'],
            [4, '图中最快的男子是？', '只保证快，不保证准'],
            [5, '图中拥有特斯拉的是？', '虽然他有特斯拉，但依然是个屌丝'],
            [6, '图中哪位不是中国籍？', '其他几个穷笔只能都是我大天朝的百姓'],
            [7, '图中谁是虹桥炮王？', '我虹桥炮王是从来不发车的'],
            [8, '图中性别与其他人都不同的是？', '提示，堡垒爱情故事'],
        ]
        rule = random.choice(rule_list)
        return CommonResponse(tip='展示验证码图片', data={'rule': rule, 'code_list': return_list})


class UserLoginView(ViewSet):
    def user_login(self, request, *args, **kwargs):
        user_ser = UserLoginSerializer(data=request.data)
        if user_ser.is_valid():
            token = user_ser.context.get('token')
            username = user_ser.context.get('user').username
            user_ident = user_ser.context.get('user').user_info.split('$')[1]
            is_complete = user_ser.context.get('user').user_info.split('$')[2]
            user_id = user_ser.context.get('user').id
            return CommonResponse(
                tip='登录成功',
                data={
                    'token': token, 'username': username,
                    'user_ident': user_ident,
                    'is_complete': is_complete,
                    'user_id': user_id
                }
            )
        else:
            error = user_ser.errors.get('non_field_errors')[0]
            return CommonResponse(state=0, tip='登录失败', error=error)


class GetUserInfoView(ViewSet):

    def get_user_info(self, request, *args, **kwargs):
        token = request.data.get('token')
        if not token:
            return CommonResponse(state=0, tip='用户未登录', error='用户未登录')
        else:
            try:
                payload = jwt_decode_handler(token)
                jwt_obj = BaseJSONWebTokenAuthentication()
                user = jwt_obj.authenticate_credentials(payload)
                user_info_mol = Info.objects.filter(user_id=user.id).first()
                user_info_ser = GetUserInfoSerialize(instance=user_info_mol)
                return CommonResponse(tip='获取用户详细信息', data=user_info_ser.data)
            except Exception as e:
                return CommonResponse(state=0, tip='用户信息验证失败', error='登录信息失效')


class UploadAvatarView(ViewSet):

    def upload_avatar(self, request, *args, **kwargs):
        user_id = request.data.get('user_id')
        user = User.objects.filter(id=user_id).first()
        avatar_name = '{}_avatar.png'.format(user.username)
        db_path = '/pic/avatar/' + avatar_name
        user_info = Info.objects.filter(user_id=user_id).first()
        user_info.avatar = db_path
        user_info.save()
        file_path = 'fooder_drf/media/pic/avatar/' + avatar_name
        with open(file_path, 'wb')as f:
            f.write(request.data.get('file').read())
        return CommonResponse(tip='修改头像成功')


class CreateTrackView(ViewSet):
    def create_track(self, request, *args, **kwargs):
        username = request.data.get('username')
        user = User.objects.filter(username=username).first()
        user_id = user.id
        stall_name = request.data.get('stall_name')
        visit_time = time.strftime('%Y-%m-%d %H:%M:%S')
        Track.objects.create(
            user_id=user_id,
            stall_name=stall_name,
            visit_time=visit_time
        )
        return CommonResponse(tip='记录足迹')


class UpdateNicknameView(ViewSet):
    def update_nickname(self, request, *args, **kwargs):
        info_ser = UpdateNicknameSerializer(data=request.data)
        if info_ser.is_valid():
            return CommonResponse(tip='昵称修改成功')
        else:
            error = info_ser.errors.get('non_field_errors')[0]
            return CommonResponse(state=0, tip='昵称修改失败', error=error)


class TrackShowView(GenericViewSet):
    queryset = Track.objects.all()
    serializer_class = TrackShowSerializer

    def get_tracks(self, request, *args, **kwargs):
        user_id = request.query_params.get('user_id')
        track_list = self.get_queryset()
        track_ser = self.get_serializer(instance=track_list, many=True)
        return_list = []
        for track in track_ser.data:
            if track.get('user_id') == user_id:
                return_list.append(track)
        n = 0
        for data in return_list:
            return_list[n]['track_num'] = n + 1
            n += 1
        return CommonResponse(tip='足迹展示', data=return_list)


class DelCouponView(ViewSet):
    def del_coupon(self, request, *args, **kwargs):
        coupon_id = request.data.get('coupon_id')
        Coupon.objects.filter(id=coupon_id).delete()
        return CommonResponse(tip='删除满减券')


class MixinCouponView(ViewSet):
    def create_coupon(self, request, *args, **kwargs):
        user_id = request.data.get('user_id')
        badge_1 = request.data.get('badge_1')
        badge_2 = request.data.get('badge_2')
        badge_3 = request.data.get('badge_3')
        badge_4 = request.data.get('badge_4')
        total_price = 80
        if badge_1 == 0:
            total_price = random.randint(70, 80)
        elif badge_1 == 1:
            total_price = random.randint(60, 70)
        elif badge_1 == 2:
            total_price = random.randint(50, 60)
        elif badge_1 == 3:
            total_price = random.randint(40, 50)
        cut_price = 5
        if badge_2 == 0:
            cut_price = random.randint(5, 10)
        elif badge_2 == 1:
            cut_price = random.randint(10, 15)
        elif badge_2 == 2:
            cut_price = random.randint(15, 20)
        elif badge_2 == 3:
            cut_price = random.randint(20, 25)
        count = 1
        n = random.randint(0, 100)
        if badge_4 == 0:
            count = 2
        elif badge_4 == 1:
            count = 3
        elif badge_4 == 2:
            count = 4
        elif badge_4 == 3:
            count = 5
        is_double = True
        if badge_3 == 0:
            is_double = bool(n < 10)
        elif badge_3 == 1:
            is_double = bool(n < 30)
        elif badge_3 == 2:
            is_double = bool(n < 50)
        elif badge_3 == 3:
            is_double = bool(n < 70)
        if not is_double:
            count = 1
        for x in range(count):
            Coupon.objects.create(
                user_id=user_id,
                total_price=total_price,
                cut_price=cut_price
            )
        msg = '合成了满{}减{}的券{}张，请刷新页面'.format(total_price, cut_price, count)
        return CommonResponse(tip='合成满减券', msg=msg)


class ResolveCouponView(ViewSet):
    def resolve_coupon(self, request, *args, **kwargs):
        coupon_id = request.data.get('coupon_id')
        coupon = Coupon.objects.filter(id=coupon_id).first()
        total_price = coupon.total_price
        cut_price = coupon.cut_price
        user_id = coupon.user_id
        count = 0
        if total_price > 60:
            count += 1
        else:
            count += 2
        if cut_price < 15:
            count += 1
        else:
            count += 2
        x = random.randint(1, 4)
        user_info = Info.objects.filter(user_id=user_id).first()
        badge_num = user_info.badge_num
        num_list = badge_num.split('$')
        new_badge_num = None
        msg = None
        if x == 1:
            msg = '分解得到了{}枚<烤熏>徽章，请刷新页面'.format(count)
            num_list[0] = str(int(num_list[0]) + count)
            new_badge_num = '$'.join(num_list)
        elif x == 2:
            msg = '分解得到了{}枚<炸煎>徽章，请刷新页面'.format(count)
            num_list[1] = str(int(num_list[1]) + count)
            new_badge_num = '$'.join(num_list)
        elif x == 3:
            msg = '分解得到了{}枚<炖炒>徽章，请刷新页面'.format(count)
            num_list[2] = str(int(num_list[2]) + count)
            new_badge_num = '$'.join(num_list)
        elif x == 4:
            msg = '分解得到了{}枚<其他>徽章，请刷新页面'.format(count)
            num_list[3] = str(int(num_list[3]) + count)
            new_badge_num = '$'.join(num_list)
        Coupon.objects.filter(id=coupon_id).delete()
        Info.objects.filter(user_id=user_id).update(badge_num=new_badge_num)
        return CommonResponse(tip='分解满减券', msg=msg)
